package com.example.springboot.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.example.springboot.service.IEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements IEmailService {
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public String sendEmail(String to) {
        int code = RandomUtil.randomInt(100000, 999999);
        SimpleMailMessage message = new SimpleMailMessage();

        //2.1设置发件人：
        message.setFrom(from);

        //2.2设置收件人
        message.setTo(to);

        //2.3邮件的主题
        message.setSubject("来自mindfall的邮件");

        //2.4设置邮件的正文
        message.setText("尊敬的用户,您好:\n" + "\n本次请求的邮件验证码为:" +
                code + ",本验证码3分钟内有效，请及时输⼊。（请勿泄露此验证码）\n"
                + "\n如⾮本⼈操作，请忽略该邮件。\n(这是⼀封⾃动发送的邮件，请不要直接回复)");

        //3.发送一封激活邮件
        try {
            javaMailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
        }
        return String.valueOf(code);
    }
}
